<?

require_once ( 'Zend/Log.php' );
require_once ( 'Zend/Log/Writer/Stream.php' );

class ErrorController extends Zend_Controller_Action {

   public function errorAction() {

      $errors = $this->_getParam( 'error_handler' );
      
      switch ( $errors->type ) {
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
            // 404 error -- controller or action not found
            $this->getResponse()->setRawHeader( 'HTTP/1.1 404 Not Found' );
            $this->view->caught = "404 - in default";
            // ... get some output to display...
            break;
         default:
            // application error; display error page, but don't change
            // status code
            // Mailing error goes here!
            // ...
            $this->view->caught = "Other - in default" . $errors->exception;
            // Log the exception:
            $exception = $errors->exception;
            $log = new Zend_Log( new Zend_Log_Writer_Stream( '/tmp/applicationException.log' ) );
            $log->debug( $exception->getMessage() . "\n" . $exception->getTraceAsString() );
            break;
      }
      
      // Works, for not. TODO: Polish it up a bit more for production servers.
      
      /* If this is an AJAX Request, process a JSON return */
      if ( $this->getRequest()->isXmlHttpRequest() ) {
         require_once('Zend/Json.php');
         
         $return = array( 'success' => false, 'errmsg' => $errors->exception->getMessage(), 
                           'errnum' => $errors->exception->getCode() );
         /* AJAX Request, return JSON */
         $json = Zend_Json::encode($return);
         
         /* Prevent the View and Layout from being redered */
         $this->_helper->layout()->disableLayout();  
         $this->_helper->viewRenderer->setNoRender();
      
         $this->getResponse()->setHeader('X-JSON', $json); // JSON header
         print $json; // JSON body for browsers like Safari which break the JSON header.
      }
      
            
   }
}
